package com.tanhua.autoconfig.template;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.tanhua.autoconfig.properties.QiNiuProperties;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class QiNiuTemplate {

    private QiNiuProperties properties;

    public QiNiuTemplate(QiNiuProperties properties) {
        this.properties = properties;
    }

    public String upload(byte[] bytes, String fileName) {
        //构造一个带指定Zone对象的配置类
//        Zone zone = properties.getEndpoint();
        Configuration cfg = new Configuration(Zone.zone2());
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
        String accessKey = properties.getAccessKey();
        String secretKey = properties.getSecretKey();
        String bucket = properties.getBucket();
//如果是Windows情况下，格式是 D:\\qiniu\\test.png
//        String localFilePath = filePath;
//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));

        try {
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

                Response response = uploadManager.put(bytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "http://r8dg5oncp.hn-bkt.clouddn.com/"+key;
    }

}
